<template>
  <div :key="data.updateKey" style="background: #fff;border-radius:10px">
    <a-tabs v-model:activeKey="data.tableKey" @change="selectTabs">
      <a-tab-pane key="1" :disabled="data.isPwdExpired" tab="基本信息">
        <div class="account-settings-info-view">
          <a-row :gutter="16">
            <a-col :md="16" :lg="16">
              <a-form ref="infoFormModel" :model="data.saveObject" :label-col="{span: 9}" :wrapper-col="{span: 10}" :rules="data.rules">
                <a-form-item label="用户登录名:">
                  <a-input v-model:value="data.saveObject.loginUsername" disabled />
                </a-form-item>
                <a-form-item label="用户姓名：" name="realname">
                  <a-input v-model:value="data.saveObject.realname" />
                </a-form-item>
                 <a-form-item label="机构号：" name="belongInfoId">
                  <a-input v-model:value="data.saveObject.belongInfoId" disabled />
                </a-form-item>
                  <a-form-item label="机构号名称：" name="agentName">
                  <a-input v-model:value="data.saveObject.agentName" disabled />
                </a-form-item>
                <a-form-item label="手机号：" name="telphone">
                  <a-input v-model:value="data.saveObject.telphone" disabled />
                </a-form-item>
                <a-form-item label="请选择性别：">
                  <a-radio-group v-model:value="data.saveObject.sex">
                    <a-radio :value="1">
                      男
                    </a-radio>
                    <a-radio :value="2">
                      女
                    </a-radio>
                  </a-radio-group>
                </a-form-item>
              </a-form>
              <a-form-item class="bottom-btn">
                <a-button type="primary" :loading="data.btnLoading" @click="changeInfo">
                  <check-circle-outlined />
                  更新基本信息
                </a-button>
              </a-form-item>
            </a-col>
            <a-col :md="8" :lg="8" :style="{ minHeight: '180px',margin:'0 auto' }">
              <!-- 原始的头像上传，带有图片裁剪功能 -->
              <!-- <div class="ant-upload-preview" @click="$refs.modal.edit(1)" > -->
              <div class="ant-upload-preview">
                <!-- <a-icon type="cloud-upload-o" class="upload-icon"/> -->
                <!-- <div class="mask">
                  <a-icon type="plus" />
                </div> -->
                <img
                  :src="data.saveObject.avatarUrl"
                  style="border: 1px solid rgba(0,0,0,0.08)"
                >

                <GzUpload
                  v-model:src="data.saveObject.avatarUrl"
                  bizType="user"
                  style="margin-top:10px"
                  :showUploadList="false"
                />
              </div>
            </a-col>
          </a-row>
          <!-- 图片裁剪组件 <avatar-modal ref="modal" @ok="setavatar"/> -->
        </div>
      </a-tab-pane>
      <a-tab-pane key="2" tab="安全信息">
        <a-tabs v-model:activeKey="data.tableKey2" tab-position="left" @change="selectTabsSub">
          <a-tab-pane key="password" tab="修改密码">
            <div class="account-settings-info-view">
              <a-row :gutter="16">
                <a-col :md="16" :lg="16">
                  <a-form ref="pwdFormModel" :model="data.updateObject" :label-col="{span: 9}" :wrapper-col="{span: 10}" :rules="data.rulesPass">
                    <a-form-item label="原密码：" name="originalPwd">
                      <a-input-password v-model:value="data.updateObject.originalPwd" autocomplete="new-password" placeholder="请输入原密码" />
                    </a-form-item>
                    <a-form-item label="新密码：" name="newPwd">
                      <a-input-password v-model:value="data.updateObject.newPwd" autocomplete="new-password" placeholder="请输入新密码" />
                    </a-form-item>
                    <a-form-item label="确认新密码：" name="confirmPwd">
                      <a-input-password v-model:value="data.updateObject.confirmPwd" autocomplete="new-password" placeholder="确认新密码" />
                    </a-form-item>
                  </a-form>
                  <a-form-item class="bottom-btn">
                    <a-button type="primary" :loading="data.btnLoading" @click="confirm">
                      <check-circle-outlined />
                      更新密码
                    </a-button>
                  </a-form-item>
                </a-col>
              </a-row>
            </div>
          </a-tab-pane>

<!--           <a-tab-pane key="mfaVer" tab="MFA认证" :disabled="data.isPwdExpired">
            <div class="account-settings-info-view">
              <a-row v-if="data.mfaInfo.mfaBindState == '0'" :gutter="12" justify="start">
                <a-col :push="2">
                  <QrcodeVue :value="data.mfaInfo.mfaBindUrl" :size="200" />
                </a-col>
                <a-col :push="3">
                  <a-alert message="" type="warning">
                    <template #description>
                      1.请使用MFA工具
                      <a-popover placement="bottom">
                        <template #content>
                          <p>推荐使用以下工具：</p>
                          <p>1. 阿里云或腾讯云手机客户端</p>
                          <p>2. 微信小程序：二次验证码</p>
                        </template>
                        <question-circle-outlined />
                      </a-popover>
                      ，扫描左侧二维码进行绑定。<br><br>
                      2.扫描完成后，输入工具内对应的验证码。<br><br>
                      注：不能扫码？
                      <a-popover placement="bottom">
                        <template #content>
                          <p>输入以下账号、秘钥进行绑定：</p>
                          <p>账号：{{ data.saveObject.telphone }}</p>
                          <p>秘钥：{{ data.mfaInfo.mfaSecretKey }}</p>
                        </template>
                        <question-circle-outlined />
                      </a-popover>
                    </template>
                  </a-alert>
                </a-col>
              </a-row>
              <a-row v-else>
                <a-col :push="2">
                  <a-alert message="" type="success">
                    <template #description>
                      已完成MFA认证。
                    </template>
                  </a-alert>
                </a-col>
              </a-row>
              <a-row :gutter="12" justify="start" type="flex" style="margin-top: 30px;">
                <a-col :md="6" :lg="6">
                  <a-form ref="mfaFormModel" :model="data.mfaInfo" :rules="data.rulesCode">
                    <a-form-item label="验证码" name="verCode">
                      <a-input v-model:value="data.mfaInfo.verCode" placeholder="请输入验证码" />
                    </a-form-item>
                  </a-form>
                  <a-form-item class="bottom-btn">
                    <a-button v-if="data.mfaInfo.mfaBindState=='0'" type="primary" :loading="data.btnLoading" @click="mfaBindConfirm">
                      <check-circle-outlined />
                      确认绑定
                    </a-button>
                    <a-button v-else type="primary" danger :loading="data.btnLoading" @click="mfaRelieveConfirm">
                      <check-circle-outlined />
                      确认解绑
                    </a-button>
                  </a-form-item>
                </a-col>
              </a-row>
            </div>
          </a-tab-pane> -->
        
        <a-tab-pane key="msg" tab="预留信息">
            <div class="account-settings-info-view">
              <a-row :gutter="16">
                <a-col :md="16" :lg="16">
                  <a-form :label-col="{span: 9}" :wrapper-col="{span: 10}">
                    <a-form-item label="预留信息：" name="">
                      <a-input v-model:value="data.safeWord" placeholder="请输入新的预留信息" show-count :maxlength="10" />
                    </a-form-item>
                  </a-form>
                  <a-form-item class="bottom-btn" style="margin-bottom: 90px;"> 
                    <a-button type="primary" :loading="data.btnLoading" @click="safeWordUpdate">
                      <check-circle-outlined />
                      确认更新
                    </a-button>
                  </a-form-item>
                </a-col>
              </a-row>
            </div>
          </a-tab-pane>
        </a-tabs>
      </a-tab-pane>
    </a-tabs>
  </div>
</template>
<script  lang="ts" setup>
import { $getUserInfo, $updateUserInfo, $updateUserPass, $getMFAInfo, $mfaBind, $mfaRelieve, upload, $getPasswordRules } from '@/api/manage'
import AvatarModal from './AvatarModal.vue'
import QrcodeVue from 'qrcode.vue'
// import store from '@/store'
import {useUserStore} from '@/store/modules/user'
import { Base64 } from 'js-base64'
import CryptoJS from "crypto-js/crypto-js"
import {ref,  reactive,onMounted,getCurrentInstance,toRaw} from 'vue'
import {message} from 'ant-design-vue'
import { getCurrentUserInfo } from '@/api/login'
import { useRoute } from 'vue-router'
const infoFormModel = ref()
const pwdFormModel = ref()
const mfaFormModel = ref()
const { $infoBox } = getCurrentInstance()!.appContext.config.globalProperties
const tabKey = ref()
const data = reactive({
  action: upload.avatar, // 上传图标地址
  btnLoading: false,
  groupKey: 'password',
  passwordRules: /^$/, //密码规则
  passwordRulesText: '', //密码规则提示文字
  safeWord:'',//预留信息
  saveObject: {
    loginUsername: '', // 登录名
    realname: '', //  真实姓名
    telphone: '',
    sex: '',
    avatarUrl: '' ,// 用户头像
    belongInfoId:'',
    agentName:'',
  },
  mfaInfo: {
    mfaBindUrl: '',
    mfaBindState: '',
    mfaSecretKey: '',
    verCode: ''
  },
  updateKey:0, //刷新键
  confirmLoading:false,
  //  avatarUrl: useUserStore().userInfo.avatarImgPath,
  updateObject: {
    originalPwd: '', // 原密码
    newPwd: '', //  新密码
    confirmPwd: '' //  确认密码
  } as any,
  recordId: useUserStore().userInfo.sysUserId, // 拿到ID
  rules: {
    realname: [{ required: true, message: '请输入真实姓名', trigger: 'blur' }]
  },
  rulesCode: {
    verCode: [{ required: true, message: '请输入验证码', trigger: 'blur' }],
  },
  rulesPass: {
    originalPwd: [{ required: true, message: '请输入原密码', trigger: 'blur' }],
    newPwd: [
      { required: false, trigger: 'blur' },{
        validator: (rule, value) => {
          if (!data.passwordRules.test(data.updateObject.newPwd)) {
            return Promise.reject(data.passwordRulesText)
          } else if(data.updateObject.newPwd !== data.updateObject.confirmPwd && data.updateObject.confirmPwd) {
            return Promise.reject('新密码与确认新密码不一致')
          } else return Promise.resolve()
        }
      }
    ],
    confirmPwd: [{ required: false, trigger: 'blur' }, {
      validator: (rule, value) => {
          if (!data.passwordRules.test(data.updateObject.confirmPwd)) {
            return Promise.reject(data.passwordRulesText)
          } else if(data.updateObject.newPwd !== data.updateObject.confirmPwd) {
            return Promise.reject('新密码与确认新密码不一致')
          } else return Promise.resolve()
        }
    }]
  },
  tableKey: '1', 
  tableKey2:'password',//第二个tabKey
  isPwdExpired: false, //是否强制改密码

})

onMounted(()=>{

  if(useRoute().query.isPwdExpired == '1'){
    data.isPwdExpired = true
    data.tableKey = '2'
  }
  if(useRoute().query.type === 'msg'){
    data.tableKey = '2'
    data.tableKey2 = 'msg'
  }

  detail()
  getPasswordRules()
})
function detail () { // 获取基本信息

  $getUserInfo().then(res => {
    data.saveObject = res
    data.safeWord = res.safeWord
  })
}
function getPasswordRules () { // 获取密码规则
  $getPasswordRules().then(res => {
    // data.passwordRules = new RegExp(res.regexpRules)
    data.passwordRules = new RegExp(res.regexpRules.replaceAll('\u0028','(').replaceAll('\u0029',')'))
    console.log(data.passwordRules)
    data.passwordRulesText = res.errTips
  })
}
function changeInfo () { // 更新基本信息事件
  infoFormModel.value.validate().then(valid =>{

    $infoBox.confirmPrimary('确认更新信息吗？', '', () => {
      data.btnLoading = true // 打开按钮上的 loading
      // that.$store.commit('showLoading') // 关闭全局刷新
      // 请求接口
      $updateUserInfo(toRaw(data.saveObject)).then(res => {
        data.btnLoading = false // 关闭按钮刷新
        //$store.commit('hideLoading') // 关闭全局刷新
        return getCurrentUserInfo()
      }).then(bizData => {
        bizData.avatarUrl = data.saveObject.avatarUrl
        bizData.realname = data.saveObject.realname
        useUserStore().refUserInfo() // 刷新用户信息
        // store.commit('SET_USER_INFO', bizData) // 调用vuex设置用户基本信息
        message.success('修改成功')
      }).catch(res => {
        //  that.$store.commit('hideLoading') // 关闭全局刷新
        data.btnLoading = false
        message.error('修改失败')
      })
    })
  })
}
function confirm (e) { // 确认更新密码
pwdFormModel.value.validate().then(valid=>{
    $infoBox.confirmPrimary('确认更新密码吗？', '', () => {
      // 请求接口
      data.btnLoading = true // 打开按钮上的 loading
      data.confirmLoading = true // 显示loading
      data.updateObject.recordId = data.recordId // 用户ID
      const copyUpdateObject = JSON.parse(JSON.stringify(data.updateObject))
      // copyUpdateObject.originalPwd = Base64.encode(copyUpdateObject.originalPwd)
      // copyUpdateObject.confirmPwd = Base64.encode(copyUpdateObject.confirmPwd)
      copyUpdateObject.originalPwd = Base64.encode(copyUpdateObject.originalPwd).toString()
      copyUpdateObject.confirmPwd = Base64.encode(copyUpdateObject.confirmPwd).toString()
      
      $updateUserPass(copyUpdateObject).then(res => {
        message.success('修改成功')
        // 退出登录
        useUserStore().logout()
      }).catch(res => {
        data.confirmLoading = false
        data.btnLoading = false
      })
    })
})
}
function selectTabs () { // 清空必填提示
  data.updateObject.originalPwd = ''
  data.updateObject.newPwd = ''
  data.updateObject.confirmPwd = ''
}
// 上传文件成功回调方法，参数value为文件地址，name是自定义参数
function  uploadSuccess (value, name) {
  data.saveObject.avatarUrl = value
  data.updateKey += 1
}


// MFA绑定
function mfaBindConfirm() {
  mfaFormModel.value.validate().then(valid =>{
    $infoBox.confirmPrimary('确认绑定MFA认证吗？', '', () => {
      // 请求接口
      data.btnLoading = true // 打开按钮上的 loading
      data.confirmLoading = true // 显示loading
      $mfaBind({verCode: data.mfaInfo.verCode}).then(res => {
        data.confirmLoading = false
        data.btnLoading = false

        getMFAInfo()
        message.success('绑定成功')
        // 退出登录
        // useUserStore().logout()
      }).catch(res => {
        data.confirmLoading = false
        data.btnLoading = false
      })
    })
  })
}

function selectTabsSub (key) { // 清空必填提示
  if (key) {
    data.groupKey = key
    detail()
  }
  // 获取MFA信息
  if(data.groupKey == 'mfaVer') {
    getMFAInfo()
  }
}

function getMFAInfo() {
  $getMFAInfo().then(res => {
    data.mfaInfo = res
  })
}

// MFA解绑
function mfaRelieveConfirm() {
  mfaFormModel.value.validate().then(valid =>{
    $infoBox.confirmPrimary('确认解绑MFA认证吗？', '', () => {
      // 请求接口
      data.btnLoading = true // 打开按钮上的 loading
      data.confirmLoading = true // 显示loading
      $mfaRelieve({verCode: data.mfaInfo.verCode}).then(res => {
        data.confirmLoading = false
        data.btnLoading = false

        getMFAInfo()
        message.success('解绑成功')
        // 退出登录
        // useUserStore().logout()
      }).catch(res => {
        data.confirmLoading = false
        data.btnLoading = false
      })
    })
  })
}
//更新预留信息
function safeWordUpdate(){
  if(!data.safeWord){
    return message.error('信息内容不可为空')
  }
  $updateUserInfo({safeWord:data.safeWord}).then(res =>{
    message.success('更新成功')
  }) 
}
</script>
<style lang="less" scoped>

.avatar-upload-wrapper {
  height: 200px;
  width: 100%;
}
.bottom-btn{
    /deep/ div{
      display: flex;
      justify-content: center;
    }
  }
.ant-upload-preview {
  display: block !important;
  text-align:center ;
  position: relative;
  margin: 0 auto;
  width: 100%;
  // max-width: 180px;
  border-radius: 50%;
  // box-shadow: 0 0 4px #ccc;

  .upload-icon {
    position: absolute;
    top: 0;
    right: 10px;
    font-size: 1.4rem;
    padding: 0.5rem;
    background: rgba(222, 221, 221, 0.7);
    border-radius: 50%;
    border: 1px solid rgba(0, 0, 0, 0.2);
  }
  .mask {
    opacity: 0;
    position: absolute;
    background: rgba(0,0,0,0.4);
    cursor: pointer;
    transition: opacity 0.4s;

    &:hover {
      opacity: 1;
    }

    i {
      font-size: 2rem;
      position: absolute;
      top: 50%;
      left: 50%;
      margin-left: -1rem;
      margin-top: -1rem;
      color: #d6d6d6;
    }
  }

  img, .mask {
    width: 150px;
    height: 150px;
    border-radius: 50%;
    overflow: hidden;
  }
}
</style>
